function strOut = jsonRead(filena)
%jsonRead - read a JSON file
%
%       STROUT = jsonRead(FILENA)
%
% The output STROUT is a struct variable whose fields/values come from 
% the JSON file FILENA.
% If FILENA is undefined, empty or does not exist, the filename can be
% interactively chosen. If the data extraction does not occur, the 
% output STROUT = [] is provided.

% G. Teza, 2022 (modification of an idea by A. Nair, 2017)

if (nargin == 1) && ~isempty(filena)
    [pathn,filen,ext] = fileparts(filena);
    if isempty(ext) || logical(sum(strcmpi(ext,{'.json','.JSON'})))
        filena = fullfile(pathn,[filen '.json']);
    end
    if ~exist(filena,'file')
        filena = [];
    end
end

if (nargin < 1) || isempty(filena) 
    [filen, pathn] = uigetfile({'*.json; *.JSON','JSON (*.json) files'},...
        'INPUT JSON FILE');
    if isequal(filen,0) || isequal(pathn,0)
        fprintf('\nNo a data file was selected \n');
        strOut = [];
        return
    else
        filena = fullfile(pathn,filen);
    end
end

fid = fopen(filena); 
raw = fread(fid,inf);       % no limits on output array
str = char(raw');           % column vector -> row vector before char conversion
fclose(fid); 
strOut = jsondecode(str);